package com.mfcxy.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mfcxy.exception.CustomException;

/**
 * 工具类
 * 
 * @author mfcxy
 *
 */
@Component
public class Tools {

	@Autowired(required = false)
	private ServletContext servletContext;
	

	/**
	 * 获取扩展名
	 * 
	 * @param originalFilename
	 * @return
	 */
	public String getExtName(String originalFilename) {
		// 根据. 拆分数组
		String[] strArr = originalFilename.split("\\.");

		// 获取扩展名
		return strArr[strArr.length - 1];
	}

	/**
	 * 将时间转换为时间戳
	 * 
	 * @param s
	 * @param format eg: yyyy-MM-dd HH:mm:ss
	 * @return
	 * @throws ParseException
	 */
	public static String dateToStamp(String s, String format) throws ParseException {
		String res;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
		Date date = simpleDateFormat.parse(s);
		long ts = date.getTime();
		res = String.valueOf(ts);
		return res;
	}

	/**
	 * 将时间戳转换为时间
	 * 
	 * @param s
	 * @param format eg: yyyy-MM-dd HH:mm:ss
	 * @return
	 */
	public static String stampToDate(String s, String format) {
		String res;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
		long lt = new Long(s);
		Date date = new Date(lt);
		res = simpleDateFormat.format(date);
		return res;
	}

	/**
	 * 单文件上传
	 * 
	 * @param file
	 * @return
	 * @throws CustomException
	 */
	public String upload(MultipartFile file) throws CustomException {
		// 获取原始文件名称
		String OriginalFilename = file.getOriginalFilename();

		// 新文件名称
		String fileName = System.currentTimeMillis() + "." + getExtName(OriginalFilename);

		// 获取年月
		String folder = Tools.stampToDate(System.currentTimeMillis() + "", "yyyy-MM");

		// 获取上传文件路径 (最终文件夹是年月)
		String path = servletContext.getRealPath("\\WEB-INF\\resources\\upload") + "\\" + folder;
		
		

		// 判断文件夹是否存在
		File pathFile = new File(path);
		
		System.out.println(path);
		
		if (!pathFile.exists() || !pathFile.isDirectory()) {
			// 不存在则创建
			System.out.println(pathFile.mkdir());
		}

		// 创建file对象
		File imagefile = new File(path + "/" + fileName);

		try {
			// 写入文件到指定位置
			file.transferTo(imagefile);
			
			if(true) {
				// Endpoint以杭州为例，其它Region请按实际情况填写。
				String endpoint = "oss-cn-shenzhen.aliyuncs.com";
				// 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。
				String accessKeyId = "LTAIKJNzHTbA7LU5";
				String accessKeySecret = "8bdnrw9uYh2ufzZuxeMvRmhByEEXau";

				// 创建OSSClient实例。
				OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

				// 上传文件流。
				InputStream inputStream = new FileInputStream(imagefile);
				PutObjectResult r = ossClient.putObject("lzfz", fileName, inputStream);
				System.err.println(r.getETag());
				System.err.println(r.getRequestId());
				//删除文件
				imagefile.delete();
				
				// 关闭OSSClient。
				ossClient.shutdown();
				return "https://lzfz.oss-cn-shenzhen.aliyuncs.com/" + fileName;
			} else {
				// 返回存储在数据库中的路径
				return "/resources/upload/" + folder + "/" + fileName;
			}
			
		} catch (IllegalStateException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new CustomException("上传文件失败");
		}
	}

	/**
	 * 多文件上传
	 * 
	 * @param files
	 * @return json 对象字符串
	 * @throws CustomException
	 * @throws JsonProcessingException
	 */
	public String uploads(List<MultipartFile> files) throws CustomException, JsonProcessingException {
		List<String> filelist = new ArrayList<String>();
		for (MultipartFile multipartFile : files) {
			filelist.add(this.upload(multipartFile));
		}
		// 用jackson工具包把对象转换成json字符串
		ObjectMapper mapper = new ObjectMapper();
		return mapper.writeValueAsString(filelist);
	}

	/**
	 * 二次md5 加密
	 * 
	 * @param password
	 * @return
	 */
	public String passwordEncryption(String password) {
		password = DigestUtils.md5DigestAsHex(password.getBytes());
		return DigestUtils.md5DigestAsHex(password.getBytes());
	}

	/**
	 * 生成uuid
	 * 
	 * @return
	 */
	public static String getUUID32() {
		String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
		return uuid;
		// return UUID.randomUUID().toString().replace("-", "").toLowerCase();
	}

	
	/*public static void main(String[] args) {
		File f = new File("E:\\共享\\code\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\blog\\WEB-INF\\resources\\upload\\2018-11");
		System.out.println(f.mkdirs());
	}*/

}
